//
//  bonusCashViewController.m
//  HQJFacilitator
//
//  Created by mymac on 16/9/21.
//  Copyright © 2016年 Fujian first time iot technology investment co., LTD. All rights reserved.
//

#import "BonusCashViewController.h"

@interface BonusCashViewController ()<UITextFieldDelegate>
{
    BOOL isHaveDian;
    BOOL isBonusNil;

}
@property (nonatomic,strong)UILabel *headerBonusLabel;
@property (nonatomic,strong)UILabel *payerLabel;
@property (nonatomic,strong)UILabel *bonusNumberLabel;
@property (nonatomic,strong)UILabel *ReceivingPartyLabel;
@property (nonatomic,strong)UILabel *TransactionPasswordLabel;
@property (nonatomic,strong)UITextField *bsNumberTextFileld;
@property (nonatomic,strong)UITextField *tPswTextFileld;
@property (nonatomic,strong)UIButton *submitButton;
@property (nonatomic,strong)UILabel *canCashLabel;
@property (nonatomic,copy)NSString *BonusStr;
@property (nonatomic,strong)UILabel *promptLabel;
@property (nonatomic,strong)UIImageView *promptImageView;

@end

@implementation BonusCashViewController

-(UIImageView *)promptImageView {
    if (!_promptImageView) {
        _promptImageView = [[UIImageView alloc]init];
        _promptImageView.layer.masksToBounds = YES;
        _promptImageView.layer.cornerRadius = 6.5;
        _promptImageView.image = [UIImage imageNamed:@"zhuyi"];
        [self.view addSubview:_promptImageView];
    }
    
    
    return _promptImageView;
}

-(UILabel *)promptLabel {
    if (!_promptLabel) {
        _promptLabel = [[UILabel alloc]init];
        _promptLabel.text= @"积分兑现比例为 2.35 个积分等于 1 元现金";
        _promptLabel.font = [UIFont systemFontOfSize:13];
        _promptLabel.textColor = [ManagerEngine getColor:@"f54949"];
        [self.view addSubview:_promptLabel];
    }
    
    return _promptLabel;
}



-(UILabel *)headerBonusLabel {
    if (!_headerBonusLabel) {
        _headerBonusLabel = [[UILabel alloc]init];
        _headerBonusLabel.backgroundColor = [ManagerEngine getColor:@"fff2b2"];
        _headerBonusLabel.frame = CGRectMake(0, 64, WIDTH, 44);
//        _headerBonusLabel.textColor = [UIColor ];
        _headerBonusLabel.textAlignment = NSTextAlignmentCenter;
        _headerBonusLabel.font = [UIFont systemFontOfSize:15 weight:.3f];
        [self.view addSubview:_headerBonusLabel];
    }
    
    
    return _headerBonusLabel;
}
-(UILabel *)payerLabel {
    
    if (!_payerLabel) {
        _payerLabel = [[UILabel alloc]init];
        _payerLabel.font = [UIFont systemFontOfSize:17];
        [self.view addSubview:_payerLabel];
    }
    
    return _payerLabel;
}
-(UILabel *)bonusNumberLabel {
    if (!_bonusNumberLabel) {
        _bonusNumberLabel = [[UILabel alloc]init];
        _bonusNumberLabel.font = [UIFont systemFontOfSize:17];
        _bonusNumberLabel.text = @"积分数:";
        [self.view addSubview:_bonusNumberLabel];

    }
    
    
    return _bonusNumberLabel;
}
-(UITextField *)bsNumberTextFileld {
    if (!_bsNumberTextFileld) {
        _bsNumberTextFileld = [[UITextField alloc]init];
        _bsNumberTextFileld.textColor = [UIColor blackColor];
        _bsNumberTextFileld.backgroundColor = [UIColor whiteColor];
        _bsNumberTextFileld.layer.masksToBounds = YES;
        _bsNumberTextFileld.layer.cornerRadius = 5;
        _bsNumberTextFileld.placeholder = @" 请输入兑现积分数额";
        _bsNumberTextFileld.clearButtonMode = UITextFieldViewModeAlways;
        _bsNumberTextFileld.keyboardType = UIKeyboardTypeDecimalPad;
        _bsNumberTextFileld.delegate = self;
        [self.view addSubview:_bsNumberTextFileld];
    }
    
    return _bsNumberTextFileld;
    
}
-(UILabel *)ReceivingPartyLabel {
    if (!_ReceivingPartyLabel) {
        _ReceivingPartyLabel = [[UILabel alloc]init];
        _ReceivingPartyLabel.font = [UIFont systemFontOfSize:17];
        [self.view addSubview:_ReceivingPartyLabel];
    }
    
    
    
    
    return _ReceivingPartyLabel;
}

-(UILabel *)TransactionPasswordLabel {
    if (!_TransactionPasswordLabel) {
        _TransactionPasswordLabel = [[UILabel alloc]init];
        _TransactionPasswordLabel.font = [UIFont systemFontOfSize:17];
        _TransactionPasswordLabel.text = @"交易密码:";
        [self.view addSubview:_TransactionPasswordLabel];
    }
    
    
    
    return _TransactionPasswordLabel;
}

-(UITextField *)tPswTextFileld {
    if (!_tPswTextFileld) {
        _tPswTextFileld = [[UITextField alloc]init];
        _tPswTextFileld.layer.masksToBounds = YES;
        _tPswTextFileld.layer.cornerRadius = 5;
        _tPswTextFileld.placeholder = @" 请输入6位交易密码";
        _tPswTextFileld.textColor = [UIColor blackColor];
        _tPswTextFileld.backgroundColor = [UIColor whiteColor];
        _tPswTextFileld.clearButtonMode = UITextFieldViewModeAlways;
        _tPswTextFileld.keyboardType = UIKeyboardTypeNumberPad;
        _tPswTextFileld.secureTextEntry = YES;
        [self.view addSubview:_tPswTextFileld];
    }
    
    
    
    return _tPswTextFileld;
}
-(UILabel *)canCashLabel {
    
    if (!_canCashLabel) {
        _canCashLabel = [[UILabel alloc]init];
        _canCashLabel.font = [UIFont systemFontOfSize:12];
        [self.view addSubview:_canCashLabel];

    }
    
    return _canCashLabel;
}


-(UIButton *)submitButton {
    if (!_submitButton) {
        _submitButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [_submitButton setTitle:@"提交" forState:UIControlStateNormal];
        _submitButton.backgroundColor = [ManagerEngine getColor:@"8ae6dc"];
        _submitButton.layer.masksToBounds = YES;
        _submitButton.layer.cornerRadius = 5;
        [self.view addSubview:_submitButton];
    }
    
    
    
    return _submitButton;
}



- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [ManagerEngine getColor:@"f5f5f5"];
    [self content];
    [self signalJudgment];
    [self requstPayClosed];
}

#pragma mark --
#pragma mark --- 视图内容
-(void)content {
    
    /******兑换比例提示******/
    CGFloat promptSize = [ManagerEngine setTextWidthStr:self.promptLabel.text andFont:[UIFont systemFontOfSize:13]];
    self.promptImageView.sd_layout.leftSpaceToView(self.view,self.view.center.x-promptSize/2-13).topSpaceToView(self.headerBonusLabel,20).heightIs(13).widthIs(13);
    
    self.promptLabel.sd_layout.leftSpaceToView(self.promptImageView,5).topEqualToView(self.promptImageView).heightIs(13).widthIs(promptSize);
    
    
    
    
    /******支付方******/
    self.payerLabel.sd_layout.
    leftSpaceToView(self.view,EDGE).
    topSpaceToView(self.promptLabel,20).
    heightIs(20).
    widthIs(WIDTH-30);
    
    /******积分数******/
    self.bonusNumberLabel.sd_layout.
    leftEqualToView(self.payerLabel).
    topSpaceToView(self.payerLabel,30).
    heightIs(20).
    widthIs(60);
    
    /******积分数输入框******/
    self.bsNumberTextFileld.sd_layout.leftSpaceToView(self.bonusNumberLabel,0).topSpaceToView(self.payerLabel,20).heightIs(40).widthIs(WIDTH-30-60);
    
    
    /****收款方*****/
   
    self.ReceivingPartyLabel.sd_layout.leftEqualToView(self.payerLabel).topSpaceToView(self.bonusNumberLabel,30).heightIs(20).widthIs(WIDTH-30);
    
    /****交易密码******/
    self.TransactionPasswordLabel.sd_layout.leftEqualToView (self.payerLabel).topSpaceToView(self.ReceivingPartyLabel,30).heightIs(20).widthIs(80);
    
    /****交易密码输入框*****/
    self.tPswTextFileld.sd_layout.leftSpaceToView(self.TransactionPasswordLabel,0).topSpaceToView(self.ReceivingPartyLabel,20).heightIs(40).widthIs(WIDTH-30-80);
    
    
    /******提交******/
    self.submitButton.sd_layout.leftEqualToView(self.payerLabel).topSpaceToView(self.tPswTextFileld,20).heightIs(40).widthIs(WIDTH-30);
    
}

#pragma mark --
#pragma mark --- 信号创建
-(void)signalJudgment {
    
    RACSignal *validPswSignal = [self.tPswTextFileld.rac_textSignal map:^id(id value) {
        return @([self isValidPsw:value]);
    }];
    RACSignal *validBounsSignal = [self.bsNumberTextFileld.rac_textSignal map:^id(NSString *value) {
        
        if ([value isEqualToString:@""]) {
            self.canCashLabel.text = [NSString stringWithFormat:@"可兑现0.00元"];
        } else {
            self.canCashLabel.text = [NSString stringWithFormat:@"可兑现%.2f元",[value floatValue]/2.35];
        }
        [self upLayout];
        return @([self textFieldChanged:value]);
    }];
    RAC(self.canCashLabel,textColor) = [validBounsSignal map:^id(NSNumber *values) {
        return [values boolValue]?[ManagerEngine getColor:@"f54949"]:[ManagerEngine getColor:@"999999"];
    }];

    
    RACSignal *signUp = [RACSignal combineLatest:@[validPswSignal,validBounsSignal] reduce:^id(NSNumber *pswValid,NSNumber *bounsValid){
        return @([pswValid boolValue]&&[bounsValid boolValue]);
    }];
    [signUp subscribeNext:^(NSNumber * signUpActive) {
        self.submitButton.enabled = [signUpActive boolValue];
        if ([signUpActive boolValue]) {
            self.submitButton.backgroundColor = [ManagerEngine getColor:@"00ccb8"];
            
        } else {
            self.submitButton.backgroundColor = [ManagerEngine getColor:@"8ae6dc"];

        }
        
    }];
    [[self.submitButton rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(id x) {
        if ([_bsNumberTextFileld.text doubleValue]>[_BonusStr doubleValue]) {
            [ManagerEngine homeSvpStr:@"亲，您的积分好像没有那么多哦" andcenterView:self.view andStyle:promptViewDefault];
        } else {
            [self submitRequst];
        }
        HQJLog(@"RACzhong  ");
    }];
    
}

-(BOOL)isValidPsw:(NSString *)text {
    if (text.length==6) {
        return YES;
    } else if (text.length >6) {
        
        [ManagerEngine homeSvpStr:@"交易密码不能超过6位数" andcenterView:self.view andStyle:promptViewDefault];
        return NO;
    } else {
        return NO;

    }
    
    
}

#pragma mark ----条件
-(BOOL)textFieldChanged:(NSString *)text
{
    if ([text floatValue]<=0) {
        return  NO;
    }  else{
        return  YES;
    }
    
}

-(void)upLayout {
    
    /***可兑换的金额***/
    
    CGFloat cancashRect = [ManagerEngine setTextWidthStr:self.canCashLabel.text  andFont:[UIFont systemFontOfSize:12]];
    self.canCashLabel.sd_layout.leftSpaceToView(self.view,WIDTH- cancashRect-15).topSpaceToView(self.bsNumberTextFileld,5).heightIs(20).widthIs(cancashRect);
    
}



#pragma mark --
#pragma mark ---UITextFiled Delegate
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    //    NSLog(@"输入的内容为%@",textField.text);
    
    if ([self.bsNumberTextFileld.text rangeOfString:@"."].location==NSNotFound) {
        isHaveDian=NO;
    }
    if ([string length]>0)
        
    {
        if ([self.bsNumberTextFileld.text length]>7)
        {
            [ManagerEngine homeSvpStr:@"亲，输入超出限制了哟" andcenterView:self.view andStyle:promptViewDefault];
            
            return NO;
        }
       
        
        unichar single=[string characterAtIndex:0];//当前输入的字符
        if ((single >='0' && single<='9') || single=='.')//数据格式正确
        {
            
            
            if (single=='.')
            {
                if(!isHaveDian)//text中还没有小数点
                {
                    isHaveDian=YES;
                    return YES;
                }else
                {
                    [ManagerEngine homeSvpStr:@"亲，您已经输入过小数点了" andcenterView:self.view andStyle:promptViewDefault];
                    
                    [self.bsNumberTextFileld.text stringByReplacingCharactersInRange:range withString:@""];
                    return NO;
                }
                
            }
            else
            {
                if (isHaveDian)//存在小数点
                {
                    //判断小数点的位数
                    NSRange ran=[self.bsNumberTextFileld.text rangeOfString:@"."];
                    
                    NSInteger tt = range.location-ran.location;
                    
                    if (tt <= 2){
                        return YES;
                    }else{
                        [ManagerEngine homeSvpStr:@"亲，您最多输入两位小数" andcenterView:self.view andStyle:promptViewDefault];
                        return NO;
                    }
                }
                else
                {
                    return YES;
                    
                }
                
                
            }
        }else{//输入的数据格式不正确
            [ManagerEngine homeSvpStr:@"亲，您输入的格式不正确" andcenterView:self.view andStyle:promptViewDefault];
            [self.bsNumberTextFileld.text stringByReplacingCharactersInRange:range withString:@""];
            return NO;
            
        }
        
    }
    
    else
    {
        return YES;
        
    }
    
}

#pragma mark --
#pragma mark --- 积分数量
-(void)bounsNumerLabel {
    
    
   self.headerBonusLabel.text = [NSString stringWithFormat:@"当前服务商账号有%@个积分",_BonusStr];
    [ManagerEngine setTextColor:self.headerBonusLabel FontNumber:[UIFont systemFontOfSize:15 weight:.2f]  AndRange:_BonusStr AndColor:[ManagerEngine getColor:@"f54949"]];
}


#pragma mark --
#pragma mark --- 名字的请求
-(void)requstPayClosed {
    

    NSString *urlStr = [NSString stringWithFormat:@"%@bonusChange/memberid/%@",AppOrg_URL,MmberidStr];
    [RequestEngine HQJFacilitatorRequestDetailsUrl:urlStr complete:^(NSDictionary *dic) {
        _BonusStr =[NSString stringWithFormat:@"%@",dic[@"bonus"]];
    
        [self bounsNumerLabel];
    self.payerLabel.text = [NSString stringWithFormat:@"支付方: %@",dic[@"realname"]];
    self.ReceivingPartyLabel.text = [NSString stringWithFormat:@"收款方: %@",dic[@"name"]];
    } andError:^(NSError *error) {
        
    } ShowHUD:YES];
    
}

#pragma mark --
#pragma mark --- 提交请求
-(void)submitRequst {
    NSString *UrlStr = [NSString stringWithFormat:@"%@bonusChangeAction/amount/%@/tradepwd/%@/memberid/%@",AppOrg_URL,self.bsNumberTextFileld.text,self.tPswTextFileld.text,MmberidStr];
    [RequestEngine HQJFacilitatorRequestDetailsUrl:UrlStr complete:^(NSDictionary *dic) {
     
        switch ([dic[@"error"]integerValue]) {
            case 45001:
                  [ManagerEngine homeSvpStr:@"交易密码错误" andcenterView:CustomWindow andStyle:promptViewFadeAway];
                break;
            case 45002:
                    [ManagerEngine homeSvpStr:@"账户积分少于兑现积分" andcenterView:CustomWindow andStyle:promptViewFadeAway];
                break;
            case 40098:
                    [ManagerEngine homeSvpStr:@"参数不全" andcenterView:CustomWindow andStyle:promptViewFadeAway];
                break;
            default:
                break;
        }
        if ([dic[@"error"]integerValue] == 0) {
            if ([dic[@"result"][@"errmsg"] isEqualToString:@"SUCCESS"]) {
                
                 _BonusStr =[NSString stringWithFormat:@"%.2f",[[Manager sharedManager].bonus floatValue]-[self.bsNumberTextFileld.text floatValue]];
                [self bounsNumerLabel];
                [ManagerEngine customAlert:@"兑换成功" andViewController:self isBack:YES];
            }
        }
    } andError:^(NSError *error) {
        
    } ShowHUD:YES];
    
    
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}



@end
